package cn.devcat.sso.config.security.handler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.devcat.sso.entity.DevcatSystemLog;
import cn.devcat.sso.service.IDevcatSystemLogService;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;

import cn.devcat.sso.config.security.SecurityMessageUtil;
import cn.devcat.sso.entity.DevcatUser;
import cn.devcat.sso.util.HttpUtil;
import cn.devcat.sso.util.JWTUtil;
import cn.devcat.sso.util.RedisUtil;
import cn.devcat.sso.util.RsUtil;
import org.springframework.web.client.RestTemplate;

/**
 * 登录成功处理器
 * @author huhailong
 *
 */
@Component
public class DevcatLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	RedisUtil redisUtil;

  @Autowired
  IDevcatSystemLogService logService;

  @Autowired
  RestTemplate restTemplate;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		DevcatUser user = JSONObject.parseObject(JSONObject.toJSONString(authentication.getPrincipal()), DevcatUser.class);
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String token = JWTUtil.sign(authentication.getName(), user.getPassword());
    CompletableFuture.runAsync(()->saveLoginSuccessLog(user.getUsername(),request));
		response.setHeader("devcat-token", uuid);
		long expireTime = 60 * 60 * 24 * 7 + 60 * 10; //比token的过期时间长了10分钟，防止redis提前过期
		redisUtil.insertOfString(uuid, token, expireTime);
		HttpUtil.sendResponse(response, RsUtil.success(SecurityMessageUtil.LOGIN_SUCCESS));
	}

  private void saveLoginSuccessLog(String username, HttpServletRequest request){
    String ipAddress = HttpUtil.getIpAddress(request);
    DevcatSystemLog log = new DevcatSystemLog();
    log.setCreateTime(LocalDateTime.now());
    log.setLogApi("/login");
    log.setLogDescribe("用户登录");
    log.setIpAddress(ipAddress);
//    log.setIpAddressLocal(getLocalByIpAddress(ipAddress));
    log.setReqTime(0L);
    log.setReqUsername(username);
  }

  private String getLocalByIpAddress(String ipAddress) {
    if("0:0:0:0:0:0:0:1".equals(ipAddress)||"127.0.0.1".equals(ipAddress)) {
      return "本机地址";
    }
    String apiUrl = "https://freeapi.ipip.net/"+ipAddress;
    ResponseEntity<String> forEntity = restTemplate.getForEntity(apiUrl, String.class);
    boolean is2xxSuccessful = forEntity.getStatusCode().is2xxSuccessful();
    StringBuilder localBuild = new StringBuilder();
    if(is2xxSuccessful) {
      JSONArray parseArray = JSONArray.parseArray(forEntity.getBody());
      for(int i=0; i<parseArray.size(); i++) {
        localBuild.append(String.valueOf(parseArray.get(i)));
        if(i < parseArray.size() - 1) {
          localBuild.append("-");
        }
      }
    }else {
      localBuild.append("暂无信息");
    }
    return localBuild.toString();
  }

}
